


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Serialization (Scala) &mdash; Akka Documentation</title>
    
    <link rel="stylesheet" href="../_static/style.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/prettify.css" type="text/css" />
    <link rel="stylesheet" href="../_static/base.css" type="text/css" />
    <link rel="stylesheet" href="../_static/docs.css" type="text/css" />
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Exo:300,400,600,700" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.0.1',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/toc.js"></script>
    <script type="text/javascript" src="../_static/prettify.js"></script>
    <script type="text/javascript" src="../_static/highlightCode.js"></script>
    <script type="text/javascript" src="../_static/effects.core.js"></script>
    <script type="text/javascript" src="../_static/effects.highlight.js"></script>
    <script type="text/javascript" src="../_static/scrollTo.js"></script>
    <script type="text/javascript" src="../_static/contentsFix.js"></script>
    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="top" title="Akka Documentation" href="../index.html" />
    <link rel="up" title="Scala API" href="index.html" />
    <link rel="next" title="FSM" href="fsm.html" />
    <link rel="prev" title="Remoting (Scala)" href="remoting.html" /> 
  </head>
  <body>
  <div class="navbar">
    <div class="navbar-inner">
      <div class="container">
        <div class="navbar-logo">
          <a href="http://akka.io"><img src="../_static/logo-small.png" /></a>
        </div>    
        <ul class="nav">
          <li><a href="http://akka.io/docs">Documentation</a></li>
          <li><a href="http://akka.io/downloads">Download</a></li>
          <li><a href="http://groups.google.com/group/akka-user">Mailing List</a></li>
          <li><a href="http://github.com/akka/akka">Code</a></li>           
          <li><a href="http://typesafe.com/products/typesafe-subscription">Commerical Support</a></li>
        </ul>
      </div>
    </div>
  </div>
  <div class="main">
    <div class="container">
      <div class="page-title">Serialization (Scala)</div><div class="pdf-link"><a href="http://akka.io/docs/akka/2.0.1/Akka.pdf"><img src="../_static/pdf-icon.png" style="height: 40px;" /></a></div></div>
    <div class="main-container">
      <div class="container">
        <div class="row">
          <div class="span12">
            <ul class="breadcrumb">           
              <li>
                 <span class="divider">|</span> <a href="fsm.html">FSM</a> <span class="divider">»</span>
              </li>
              <li>
                <a href="../index.html">Contents</a>
              </li>
              <li>
                <span class="divider">«</span> <a href="remoting.html">Remoting (Scala)</a> <span class="divider">|</span>
              </li>
              <li>
                Version 2.0.1
              </li>
            </ul>         
          </div>
        </div>
        <div class="row">
          <div class="span9">
            
  <div class="section" id="serialization-scala">
<span id="id1"></span><h1>Serialization (Scala)</h1>
<p>Akka has a built-in Extension for serialization,
and it is both possible to use the built-in serializers and to write your own.</p>
<p>The serialization mechanism is both used by Akka internally to serialize messages,
and available for ad-hoc serialization of whatever you might need it for.</p>
<div class="section" id="usage">
<h2>Usage</h2>
<div class="section" id="configuration">
<h3>Configuration</h3>
<p>For Akka to know which <tt class="docutils literal"><span class="pre">Serializer</span></tt> to use for what, you need edit your <a class="reference internal" href="../general/configuration.html#configuration"><em>Configuration</em></a>,
in the &#8220;akka.actor.serializers&#8221;-section you bind names to implementations of the <tt class="docutils literal"><span class="pre">akka.serialization.Serializer</span></tt>
you wish to use, like this:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">config</span> <span class="k">=</span> <span class="nc">ConfigFactory</span><span class="o">.</span><span class="n">parseString</span><span class="o">(</span><span class="s">&quot;&quot;&quot;</span>
<span class="s">  akka {</span>
<span class="s">    actor {</span>
<span class="s">      serializers {</span>
<span class="s">        java = &quot;akka.serialization.JavaSerializer&quot;</span>
<span class="s">        proto = &quot;akka.serialization.ProtobufSerializer&quot;</span>
<span class="s">        myown = &quot;akka.docs.serialization.MyOwnSerializer&quot;</span>
<span class="s">      }</span>
<span class="s">    }</span>
<span class="s">  }</span>
<span class="s">&quot;&quot;&quot;</span><span class="o">)</span>
</pre></div>
</div>
<p>After you&#8217;ve bound names to different implementations of <tt class="docutils literal"><span class="pre">Serializer</span></tt> you need to wire which classes
should be serialized using which <tt class="docutils literal"><span class="pre">Serializer</span></tt>, this is done in the &#8220;akka.actor.serialization-bindings&#8221;-section:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">config</span> <span class="k">=</span> <span class="nc">ConfigFactory</span><span class="o">.</span><span class="n">parseString</span><span class="o">(</span><span class="s">&quot;&quot;&quot;</span>
<span class="s">  akka {</span>
<span class="s">    actor {</span>
<span class="s">      serializers {</span>
<span class="s">        java = &quot;akka.serialization.JavaSerializer&quot;</span>
<span class="s">        proto = &quot;akka.serialization.ProtobufSerializer&quot;</span>
<span class="s">        myown = &quot;akka.docs.serialization.MyOwnSerializer&quot;</span>
<span class="s">      }</span>

<span class="s">      serialization-bindings {</span>
<span class="s">        &quot;java.lang.String&quot; = java</span>
<span class="s">        &quot;akka.docs.serialization.Customer&quot; = java</span>
<span class="s">        &quot;com.google.protobuf.Message&quot; = proto</span>
<span class="s">        &quot;akka.docs.serialization.MyOwnSerializable&quot; = myown</span>
<span class="s">        &quot;java.lang.Boolean&quot; = myown</span>
<span class="s">      }</span>
<span class="s">    }</span>
<span class="s">  }</span>
<span class="s">&quot;&quot;&quot;</span><span class="o">)</span>
</pre></div>
</div>
<p>You only need to specify the name of an interface or abstract base class of the
messages. In case of ambiguity, i.e. the message implements several of the
configured classes, the most specific configured class will be used, i.e. the
one of which all other candidates are superclasses. If this condition cannot be
met, because e.g. <tt class="docutils literal"><span class="pre">java.io.Serializable</span></tt> and <tt class="docutils literal"><span class="pre">MyOwnSerializable</span></tt> both apply
and neither is a subtype of the other, a warning will be issued</p>
<p>Akka provides serializers for <tt class="xref py py-class docutils literal"><span class="pre">java.io.Serializable</span></tt> and <a class="reference external" href="http://code.google.com/p/protobuf/">protobuf</a>
<tt class="xref py py-class docutils literal"><span class="pre">com.google.protobuf.GeneratedMessage</span></tt> by default (the latter only if
depending on the akka-remote module), so normally you don&#8217;t need to add
configuration for that; since <tt class="xref py py-class docutils literal"><span class="pre">com.google.protobuf.GeneratedMessage</span></tt>
implements <tt class="xref py py-class docutils literal"><span class="pre">java.io.Serializable</span></tt>, protobuf messages will always by
serialized using the protobuf protocol unless specifically overridden. In order
to disable a default serializer, map its marker type to “none”:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="n">akka</span><span class="o">.</span><span class="n">actor</span><span class="o">.</span><span class="n">serialization</span><span class="o">-</span><span class="n">bindings</span> <span class="o">{</span>
  <span class="s">&quot;java.io.Serializable&quot;</span> <span class="k">=</span> <span class="n">none</span>
<span class="o">}</span>
</pre></div>
</div>
</div>
<div class="section" id="verification">
<h3>Verification</h3>
<p>If you want to verify that your messages are serializable you can enable the following config option:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">config</span> <span class="k">=</span> <span class="nc">ConfigFactory</span><span class="o">.</span><span class="n">parseString</span><span class="o">(</span><span class="s">&quot;&quot;&quot;</span>
<span class="s">  akka {</span>
<span class="s">    actor {</span>
<span class="s">      serialize-messages = on</span>
<span class="s">    }</span>
<span class="s">  }</span>
<span class="s">&quot;&quot;&quot;</span><span class="o">)</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">We only recommend using the config option turned on when you&#8217;re running tests.
It is completely pointless to have it turned on in other scenarios.</p>
</div>
<p>If you want to verify that your <tt class="docutils literal"><span class="pre">Props</span></tt> are serializable you can enable the following config option:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">val</span> <span class="n">config</span> <span class="k">=</span> <span class="nc">ConfigFactory</span><span class="o">.</span><span class="n">parseString</span><span class="o">(</span><span class="s">&quot;&quot;&quot;</span>
<span class="s">  akka {</span>
<span class="s">    actor {</span>
<span class="s">      serialize-creators = on</span>
<span class="s">    }</span>
<span class="s">  }</span>
<span class="s">&quot;&quot;&quot;</span><span class="o">)</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">We only recommend using the config option turned on when you&#8217;re running tests.
It is completely pointless to have it turned on in other scenarios.</p>
</div>
</div>
<div class="section" id="programmatic">
<h3>Programmatic</h3>
<p>If you want to programmatically serialize/deserialize using Akka Serialization,
here&#8217;s some examples:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.serialization._</span>
<span class="k">import</span> <span class="nn">com.typesafe.config.ConfigFactory</span>

    <span class="k">val</span> <span class="n">system</span> <span class="k">=</span> <span class="nc">ActorSystem</span><span class="o">(</span><span class="s">&quot;example&quot;</span><span class="o">)</span>

    <span class="c1">// Get the Serialization Extension</span>
    <span class="k">val</span> <span class="n">serialization</span> <span class="k">=</span> <span class="nc">SerializationExtension</span><span class="o">(</span><span class="n">system</span><span class="o">)</span>

    <span class="c1">// Have something to serialize</span>
    <span class="k">val</span> <span class="n">original</span> <span class="k">=</span> <span class="s">&quot;woohoo&quot;</span>

    <span class="c1">// Find the Serializer for it</span>
    <span class="k">val</span> <span class="n">serializer</span> <span class="k">=</span> <span class="n">serialization</span><span class="o">.</span><span class="n">findSerializerFor</span><span class="o">(</span><span class="n">original</span><span class="o">)</span>

    <span class="c1">// Turn it into bytes</span>
    <span class="k">val</span> <span class="n">bytes</span> <span class="k">=</span> <span class="n">serializer</span><span class="o">.</span><span class="n">toBinary</span><span class="o">(</span><span class="n">original</span><span class="o">)</span>

    <span class="c1">// Turn it back into an object</span>
    <span class="k">val</span> <span class="n">back</span> <span class="k">=</span> <span class="n">serializer</span><span class="o">.</span><span class="n">fromBinary</span><span class="o">(</span><span class="n">bytes</span><span class="o">,</span> <span class="n">manifest</span> <span class="k">=</span> <span class="nc">None</span><span class="o">)</span>

    <span class="c1">// Voilá!</span>
    <span class="n">back</span> <span class="n">must</span> <span class="n">equal</span><span class="o">(</span><span class="n">original</span><span class="o">)</span>
</pre></div>
</div>
<p>For more information, have a look at the <tt class="docutils literal"><span class="pre">ScalaDoc</span></tt> for <tt class="docutils literal"><span class="pre">akka.serialization._</span></tt></p>
</div>
</div>
<div class="section" id="customization">
<h2>Customization</h2>
<p>So, lets say that you want to create your own <tt class="docutils literal"><span class="pre">Serializer</span></tt>,
you saw the <tt class="docutils literal"><span class="pre">akka.docs.serialization.MyOwnSerializer</span></tt> in the config example above?</p>
<div class="section" id="creating-new-serializers">
<h3>Creating new Serializers</h3>
<p>First you need to create a class definition of your <tt class="docutils literal"><span class="pre">Serializer</span></tt> like so:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.serialization._</span>
<span class="k">import</span> <span class="nn">com.typesafe.config.ConfigFactory</span>

<span class="k">class</span> <span class="nc">MyOwnSerializer</span> <span class="k">extends</span> <span class="nc">Serializer</span> <span class="o">{</span>

  <span class="c1">// This is whether &quot;fromBinary&quot; requires a &quot;clazz&quot; or not</span>
  <span class="k">def</span> <span class="n">includeManifest</span><span class="k">:</span> <span class="kt">Boolean</span> <span class="o">=</span> <span class="kc">false</span>

  <span class="c1">// Pick a unique identifier for your Serializer,</span>
  <span class="c1">// you&#39;ve got a couple of billions to choose from,</span>
  <span class="c1">// 0 - 16 is reserved by Akka itself</span>
  <span class="k">def</span> <span class="n">identifier</span> <span class="k">=</span> <span class="mi">1234567</span>

  <span class="c1">// &quot;toBinary&quot; serializes the given object to an Array of Bytes</span>
  <span class="k">def</span> <span class="n">toBinary</span><span class="o">(</span><span class="n">obj</span><span class="k">:</span> <span class="kt">AnyRef</span><span class="o">)</span><span class="k">:</span> <span class="kt">Array</span><span class="o">[</span><span class="kt">Byte</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
    <span class="c1">// Put the code that serializes the object here</span>
    <span class="c1">// ... ...</span>
  <span class="o">}</span>

  <span class="c1">// &quot;fromBinary&quot; deserializes the given array,</span>
  <span class="c1">// using the type hint (if any, see &quot;includeManifest&quot; above)</span>
  <span class="c1">// into the optionally provided classLoader.</span>
  <span class="k">def</span> <span class="n">fromBinary</span><span class="o">(</span><span class="n">bytes</span><span class="k">:</span> <span class="kt">Array</span><span class="o">[</span><span class="kt">Byte</span><span class="o">],</span>
                 <span class="n">clazz</span><span class="k">:</span> <span class="kt">Option</span><span class="o">[</span><span class="kt">Class</span><span class="o">[</span><span class="k">_</span><span class="o">]])</span><span class="k">:</span> <span class="kt">AnyRef</span> <span class="o">=</span> <span class="o">{</span>
    <span class="c1">// Put your code that deserializes here</span>
    <span class="c1">// ... ...</span>
  <span class="o">}</span>
<span class="o">}</span>
</pre></div>
</div>
<p>Then you only need to fill in the blanks, bind it to a name in your <a class="reference internal" href="../general/configuration.html#configuration"><em>Configuration</em></a> and then
list which classes that should be serialized using it.</p>
</div>
<div class="section" id="serializing-actorrefs">
<h3>Serializing ActorRefs</h3>
<p>All ActorRefs are serializable using JavaSerializer, but in case you are writing your own serializer,
you might want to know how to serialize and deserialize them properly, here&#8217;s the magic incantation:</p>
<div class="highlight-scala"><div class="highlight"><pre><span class="k">import</span> <span class="nn">akka.serialization._</span>
<span class="k">import</span> <span class="nn">com.typesafe.config.ConfigFactory</span>

    <span class="c1">// Serialize</span>
    <span class="c1">// (beneath toBinary)</span>

    <span class="c1">// If there is no transportAddress,</span>
    <span class="c1">// it means that either this Serializer isn&#39;t called</span>
    <span class="c1">// within a piece of code that sets it,</span>
    <span class="c1">// so either you need to supply your own,</span>
    <span class="c1">// or simply use the local path.</span>
    <span class="k">val</span> <span class="n">identifier</span><span class="k">:</span> <span class="kt">String</span> <span class="o">=</span> <span class="nc">Serialization</span><span class="o">.</span><span class="n">currentTransportAddress</span><span class="o">.</span><span class="n">value</span> <span class="k">match</span> <span class="o">{</span>
      <span class="k">case</span> <span class="kc">null</span>    <span class="k">⇒</span> <span class="n">theActorRef</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">toString</span>
      <span class="k">case</span> <span class="n">address</span> <span class="k">⇒</span> <span class="n">theActorRef</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">toStringWithAddress</span><span class="o">(</span><span class="n">address</span><span class="o">)</span>
    <span class="o">}</span>
    <span class="c1">// Then just serialize the identifier however you like</span>

    <span class="c1">// Deserialize</span>
    <span class="c1">// (beneath fromBinary)</span>
    <span class="k">val</span> <span class="n">deserializedActorRef</span> <span class="k">=</span> <span class="n">theActorSystem</span> <span class="n">actorFor</span> <span class="n">identifier</span>
    <span class="c1">// Then just use the ActorRef</span>
</pre></div>
</div>
</div>
<div class="section" id="deep-serialization-of-actors">
<h3>Deep serialization of Actors</h3>
<p>The current recommended approach to do deep serialization of internal actor state is to use Event Sourcing,
for more reading on the topic, see these examples:</p>
<p><a class="reference external" href="http://krasserm.blogspot.com/2011/11/building-event-sourced-web-application.html">Martin Krasser on EventSourcing Part1</a></p>
<p><a class="reference external" href="http://krasserm.blogspot.com/2012/01/building-event-sourced-web-application.html">Martin Krasser on EventSourcing Part2</a></p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Built-in API support for persisting Actors will come in a later release, see the roadmap for more info:</p>
<p class="last"><a class="reference external" href="https://docs.google.com/a/typesafe.com/document/d/18W9-fKs55wiFNjXL9q50PYOnR7-nnsImzJqHOPPbM4E">Akka 2.0 roadmap</a></p>
</div>
</div>
</div>
<div class="section" id="a-word-about-java-serialization">
<h2>A Word About Java Serialization</h2>
<p>When using Java serialization without employing the <tt class="xref py py-class docutils literal"><span class="pre">JavaSerializer</span></tt> for
the task, you must make sure to supply a valid <tt class="xref py py-class docutils literal"><span class="pre">ExtendedActorSystem</span></tt> in
the dynamic variable <tt class="docutils literal"><span class="pre">JavaSerializer.currentSystem</span></tt>. This is used when
reading in the representation of an <tt class="xref py py-class docutils literal"><span class="pre">ActorRef</span></tt> for turning the string
representation into a real reference. <tt class="xref py py-class docutils literal"><span class="pre">DynamicVariable</span></tt> is a
thread-local variable, so be sure to have it set while deserializing anything
which might contain actor references.</p>
</div>
</div>


          </div>
          <div class="span3"><p class="contents-title">Contents</p>
              <div id="scroller-anchor">
                <div id="scroller">
                  <div id="toc"></div>
                </div>
              </div></div>
        </div>
      </div>
    </div>
  </div>
  <div class="footer">
  <div class="container">
    <ul>
      <li><h5>Akka</h5></li>
      <li><a href="http://akka.io/docs">Documentation</a></li>
      <li><a href="http://akka.io/downloads">Downloads</a></li>
    </ul>
    <ul>
      <li><h5>Contribute</h5></li>
      <li><a href="http://github.com/akka/akka">Source Code</a></li>
      <li><a href="http://groups.google.com/group/akka-user">Mailing List</a></li>      
      <li><a href="http://www.assembla.com/spaces/akka/tickets">Report a Bug</a></li>      
    </ul>
    <ul>
      <li><h5>Company</h5></li>
      <li><a href="http://typesafe.com/products/typesafe-subscription">Commercial Support</a></li>
      <li><a href="http://akka.io/team">Team</a></li>
      <li><a href="mailto:info@typesafe.com">Contact</a></li>
    </ul>
    <ul>
      <li><img src="../_static/watermark.png" align="center"/></li>
    </ul>
  </div>
  <div class="container copyright">
    <p style="float: left;">
      © 2012 <a href="http://typesafe.com/">Typesafe Inc.</a> <span class="license">Akka is Open Source and available under the Apache 2 License.</span>
    </p>
    <p style="float: right; font-size: 12px;">
      Last updated: Apr 13, 2012
    </p>          
  </div>
</div>
<script type="text/javascript">
  $('#toc').toc();
</script>
  

  </body>
</html>